import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// 提前注册路由守卫，确保首次导航受保护
import './permission'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

// Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

// 样式
import './styles/index.scss'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 权限指令
import { setupDirectives } from './directives'

// 🔧 初始化认证
import { getToken, updateAxiosAuthHeader } from '@/utils/auth'

// ✅ "记住我"功能：启动时检查
import { checkRememberMeOnStartup } from '@/config/storage'

// 配置进度条
NProgress.configure({ showSpinner: false })

const app = createApp(App)

// Pinia状态管理
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

// 初始化应用（动态路由与鉴权在 src/permission.ts 中处理）
async function bootstrap() {
  // ✅ 第一步：检查"记住我"选项，决定是否保留认证数据
  checkRememberMeOnStartup()
  
  // 🔧 在应用启动时初始化axios认证header
  const existingToken = getToken()
  if (existingToken) {
    updateAxiosAuthHeader(existingToken)
    console.log('🔄 应用启动时检测到已保存token，已初始化axios header')
  }
  
  // 先挂载 Pinia 以便使用各个 store
  app.use(pinia)

  // Element Plus配置
  app.use(ElementPlus, {
    locale: zhCn,
    size: (localStorage.getItem('kexio-app-store') && JSON.parse(localStorage.getItem('kexio-app-store') as string)?.size) || 'default'
  })

  // 指令
  setupDirectives(app)

  // 在挂载路由前预初始化动态路由，解决刷新后首个深链无匹配的问题
  try {
    const { useUserStore } = await import('@/stores/user')
    const { usePermissionStore } = await import('@/stores/permission')
    const userStore = useUserStore()
    const permissionStore = usePermissionStore()
    
    if (userStore.token) {
      if (!userStore.userInfo) {
        await userStore.getUserInfo()
      }
      // 即使 menuLoaded=true，如果路由未挂载或版本不一致，也需要重新生成/挂载
      const needsLoad = !permissionStore.menuLoaded || 
                        !permissionStore.routesMounted ||
                        permissionStore.permVersion !== userStore.permVersion
      
      if (needsLoad) {
        await permissionStore.generateRoutes()
      }
    }
  } catch (e) {
    console.warn('[bootstrap] pre-init skipped:', e)
  }

  // 路由
  app.use(router)

  app.mount('#app')
}

bootstrap()
